import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/Home/HomeView.vue'
import LoginView from '@/views/Home/components/LoginView.vue'
import RegisterView from '@/views/Home/components/RegisterView.vue'
import RetrieveView from '@/views/Home/components/RetrieveView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      children: [
        { path: '', name: 'login', component: LoginView },
        { path: 'register', name: 'register', component: RegisterView },
        { path: 'retrieve', name: 'retrieve', component: RetrieveView },
      ],
    },
    {
      path: '/common',
      name: 'common',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/About/CommonView.vue')
    },
    {
      path: '/traffic',
      name: 'traffic',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/About/TrafficView.vue')
    },
    {
      path: '/admin',
      name: 'admin',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/About/AdminView.vue')
    }
  ]
})
// eslint-disable-next-line no-unused-vars
router.beforeEach((to, from, next) => {
  const localInfo = JSON.parse(localStorage.getItem('account'))

  // 检查是否需要重定向
  if (to.name == 'common' || to.name == 'traffic' || to.name == 'admin') {
    if (localInfo) {
      // 这样子判断有两个好处，
      // 1、不管我输入的地址是 /traafic || /admin || /common 都会直接跳转到localstore中type所对应的页面
      // 2、next()的时候 也会触发路由守卫，如果不加一个 ！== ，会进入无限循环
      if (localInfo.type === 'common' && to.name !== 'common') {
        console.log(localInfo);
        next('/common');
      } else if (localInfo.type === 'traffic' && to.name !== 'traffic') {
        next({ name: 'traffic' });
      } else if (localInfo.type === 'admin' && to.name !== 'admin') {
        next({ name: 'admin' });
      } else {
        next(); // 如果当前已经是目标路由，则继续
      }
    } else {
      next({ name: 'login' }); 
    }
  } else {
    next(); // 继续其他路由
  }
});



export default router
